<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/1/8
 * Time: 11:05
 */
namespace common\logics\smscode;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;
use common\services\message\ChuanglanSmsApi;


class SmsCodeLogic extends BaseObject implements ISmsCode
{
    /** @var \common\sources\read\smscode\SmsCodeAccess $RSmsCodeAccess ***/
    private $RSmsCodeAccess;
    /** @var \common\sources\write\smscode\SmsCodeAccess $WSmsCodeAccess **/
    private $WSmsCodeAccess;
    /** @var \common\sources\read\adminuser\AdminUserAccess $RAdminUserAccess **/
    private $RAdminUserAccess;


    public function init()
    {
        $this->RSmsCodeAccess = Yii::$container->get("RSmsCodeAccess");
        $this->WSmsCodeAccess = Yii::$container->get("WSmsCodeAccess");
        $this->RAdminUserAccess = Yii::$container->get('RAdminUserAccess');
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function getSmsCode($data)
    {
        if(empty($data['phone']))
        {
            return Tool::returnJson([],401,"手机号码不能为空");
        }
        $smscodes = $this->RSmsCodeAccess->getPhoneCode($data);
        if(count($smscodes) >0)
        {
            foreach($smscodes as &$codes)
            {
                $codes['sendtime'] = isset($codes['sendtime']) ? date('Y-m-d H:i:s',$codes['sendtime']) : '';
                $codes['status_name'] =  isset($codes['status']) ? Yii::$app->params['sms_config']['sms_status_name'][$codes['status']] : "未知状态";
            }
        }
        return Tool::returnJson($smscodes,200,"成功");
    }

    public function sendSmsCode($data)
    {
        $clapi = new ChuanglanSmsApi();
        $verifycode = rand(100000, 999999);
        if(empty($data['phone'])){
            return Tool::returnJson($data = [], $code = 401, '发送短信手机号码不能为空');
        }
        if(empty($data['sms_type'])){
            return Tool::returnJson($data = [], $code = 402, '发送短信类型不能为空');
        }
        if(!Tool::isPhone($data['phone'])){
            return Tool::returnJson($data = [], $code = 403, '手机号码类型有误');
        }
        //校验设备号是否能够登陆
//        $equipment = [];
//        @exec("ipconfig /all", $equipment);
//        if ( !$equipment )
//        {
//            $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";
//            if ( is_file($ipconfig) )
//                @exec($ipconfig." /all", $equipment);
//            else
//                @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $equipment);
//        }
//        $err = explode(":",$equipment[13]);
//        $equips = Yii::$app->params['equip_addr'];
//        if(!in_array(trim($err[1]),$equips))
//        {
//            return Tool::returnJson([],405,"该机器不能登陆");
//        }
        //登陆时检测是否注册
        if ($data['sms_type'] == 'login_user')
        {
            $user = $this->RAdminUserAccess->getDetial($data['phone']);
            if (empty($user)) {
                return Tool::returnJson($data = [], $code = 405, '手机号还未注册，请先注册后操作');
            }
        }else
         {
            return Tool::returnJson([],406,"短信验证类型有误");
        }
        $data['verifycode'] = $verifycode;
        $data['sendtime'] = time();
        $data['smstype'] = Yii::$app->params['sms_config']['sms_type'][$data['sms_type']];

        //更改发送短文字信息
        $msg = Yii::$app->params['sms_config']['sms_msg']['common_msg'];
        //控制短信发送时间
        $sms = $this->RSmsCodeAccess->getSmsCode(['phone'=> $data['phone'],'type' => $data['smstype']]);
        if(time()-$sms['sendtime']<60){
            return Tool::returnJson($data = [], $code = 511, '60秒内不能重复发送');
        }
        //短信发送记录检测
        $smsNumber = $this->smsAuth($data);
        if ($smsNumber >= Yii::$app->params['sms_config']['sms_max']) {
            return Tool::returnJson($data = [], $code = 407, '今日验证码发送次数已达上限');
        }
        try{
            $params = $data['phone'] . "," . $verifycode;
            //调用短信发送api
            $result = $clapi->sendVariableSMS($msg, $params);
            if (!is_null(json_decode($result))) {
                $output = json_decode($result, true);
                if (isset($output['code']) && $output['code'] == '0') {
                    unset($data['sms_type']);
                    $data['type'] = $data['smstype'];
                    $this->WSmsCodeAccess->addSmsCode($data);
                    return Tool::returnJson($data = [], $code = 200, '发送成功');
                } else {
                    $msg = $output['errorMsg'];
                    return Tool::returnJson($data = [], $code = 408, $msg);
                }
            } else {
                return Tool::returnJson($data = [], $code = 409, $result);
            }
        }catch (\Exception $e){
            return Tool::returnJson([],510, "发送短信验证码异常".$e->getMessage());
        }
    }

    public function resetCode($data)
    {
        if(empty($data['phone']))
        {
            return Tool::returnJson([],401,"手机号码不能为空");
        }
        $data['today'] = strtotime(date("Y-m-d"), time());
        $data['endtoday'] = $data['today'] + 60 * 60 * 24;
        //查询改手机号码今天发送次数
        $phone_count = $this->RSmsCodeAccess->getSms($data);
        if($phone_count<5)
        {
            return Tool::returnJson([],402,"手机号码发送次数没有达到上线不能重置");
        }
        //重置操作
        $result = $this->WSmsCodeAccess->delPhoneCode($data['phone']);
        if(!$result)
        {
            return Tool::returnJson([],403,"重置失败");
        }
        return Tool::returnJson([],200,"成功");
    }

    //发送记录检测方法
    private function smsAuth($data)
    {
        $data['today'] = strtotime(date("Y-m-d"), time());
        $data['endtoday'] = $data['today'] + 60 * 60 * 24;
        $smsNumber = $this->RSmsCodeAccess->getSms($data);
        return $smsNumber;
    }
}